package com.clip.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import sun.misc.BASE64Decoder;

import com.clip.action.util.CookieAttributeKey;
import com.clip.action.util.SessionAttributeKey;
import com.clip.entity.User;
import com.clip.entity.Userassina;
import com.clip.service.UserService;
import com.clip.util.Functions;

@Controller
@Scope("prototype")
public class CheckLoginFilter implements Filter{
	@Autowired
	private UserService userService;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession(true);
		User user = (User)session.getAttribute(SessionAttributeKey.USER);
		if(user==null){
			Cookie[] cookies=req.getCookies(); 
			if(cookies!=null){
				for(Cookie cookie: cookies){
					if(cookie.getName().equals(CookieAttributeKey.COOKIENAME)){
						if(cookie.getValue()!=null&&cookie.getValue()!=""){
							String cookieInfo = cookie.getValue();
							BASE64Decoder decode = new BASE64Decoder();
					        String tmp=new String(decode.decodeBuffer(cookieInfo));
					        if(tmp.indexOf(",")>0){
								String[] c = new String(tmp).split(",");
								if(c[1].equals("auto")){
									user = userService.getUserByEmail(c[0]);
									session.setAttribute(SessionAttributeKey.USER, user);
								}
					        }
						}
					}else if(cookie.getName().equals(CookieAttributeKey.COOKIESINAUID)){
						if(cookie.getValue()!=null&&cookie.getValue().length()>1){
							String cookievalue = cookie.getValue();
							String sinauidstr=Functions.base64_decode(cookievalue);
							if(sinauidstr.indexOf(",")>0){
								String[] c = sinauidstr.split(",");
								if(c[1].equals("auto")){
									Userassina userassina= userService.getAndUpdateUserassina(c[0], null);
									User currentUser=this.userService.getUserById(userassina.getUid());
									session.setAttribute(SessionAttributeKey.USER, currentUser);
									session.setAttribute(SessionAttributeKey.USERASSINA, userassina);
								}
							}
						}
					}
				}
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
